package com.study.spmongodb.wwj.thread2.char16;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author study
 * @version 1.0
 * @date 2020/12/9 10:23
 */
public class AppServer extends Thread {
    private static final int DEFAULT_PORT = 12722;
    private final ExecutorService executor = Executors.newFixedThreadPool(10);
    ServerSocket server;
    private int port;
    private volatile boolean start = true;
    private List<ClientHandler> clientHandlers = new ArrayList<>();

    public AppServer() {
        this(DEFAULT_PORT);
    }

    public AppServer(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        System.out.println("server start!");
        try {
            server = new ServerSocket(port);
            while (start) {
                Socket client = server.accept();
                ClientHandler task = new ClientHandler(client);
                executor.submit(task);
                this.clientHandlers.add(task);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private void dispose() {
        clientHandlers.stream().forEach(ClientHandler::stop);
        this.executor.shutdown();
    }

    public void shutdown() throws IOException {
        this.start = false;
        this.interrupt();
        this.server.close();
    }
}
